<?php

session_start();
include_once("function/util.php");
$username = $_POST['username'];
$password = $_POST['password'];

$pat_account = "/^[a-zA-Z0-9]{5,15}$/";
$pat_email = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/";
$err_msg = "";
if (strlen($username) < 1) {
    $err_msg = "displayerror('ท่านยังไม่ได้ใส่ชื่อ');";
} else if (strlen($password) < 1) {
    $err_msg = "displayerror('ท่านยังไม่ได้ใส่ password');";
} else {
    $sql = "SELECT * FROM user WHERE user_name='$username' AND user_password='$password'";
    //$sql = addslashes($sql);

    $result = runSQL($sql);


    if (runSQL_num_row($result) != 1) {
        $err_msg = "displayerror('คุณใส่ Username หรือ Password ผิด');";
    } else {
        $user = mysql_fetch_array($result);
        if ($user['is_active'] == 0) {
            $err_msg = "displayerror('Username ของคุณถูกยกเลิกแล้ว');";
        }
    }
}

if ($err_msg != "") {
    echo $err_msg;
    exit();
} // print error massage and exit
//$user = mysql_fetch_array($result);
$_SESSION['admin_user_id'] = $user['user_id'];
$_SESSION['admin_user_name'] = $user['user_name'];
$_SESSION['admin_user_type'] = $user['user_type'];

$cookie_name = "login";
if (isset($_POST['loginkeeping'])) {

    $value = $user['user_name'];
    $expire = time() + 30 * 24 * 60 * 60; //จำนวนวินาทีของ 30 วัน
    setcookie($cookie_name, $value, $expire);
} else {
    setcookie($cookie_name, '', 0);
}

$err_msg = "loadmainpage();";
mysql_close($conn);

echo $err_msg;